package org.sny7.openOfflineList.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

public class LanguageChanger {
	
	private static Properties currentLanguageProperties = new Properties();
	
	private static Map<Object, String> componentMap = new HashMap<Object, String>();
	
	private static String currentLanguage = "";
	
	public static String getCurrentLanguage() {
		return currentLanguage;
	}

	public static void change(String fileName) {
		load(fileName);
		applyAll();
	}
	
	public static void load(String fileName) {
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(fileName);
			Properties properties = new Properties();
			properties.load(fileInputStream);
			currentLanguageProperties = properties;
			currentLanguage = fileName;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fileInputStream != null) {
					fileInputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private static void applyAll() {
		for (Entry<Object, String> entry : componentMap.entrySet()) {
			localeThis(entry.getKey(), entry.getValue());
		}
	}
	
	private static String getString(String key) {
		return (String) currentLanguageProperties.get(key);
	}
	
	private static String generateToolTipText(String text) {
		if (!text.contains("\n")) {
			return text;
		}
		text = "<html>" + text.replaceAll("\n", "<br/>") + "</html>";
		return text;
	}

	@SuppressWarnings("unchecked")
	public static void localeThis(Object object, String name) {
		if (name != null && !name.contains(".") && name.contains("-")) {
			componentMap.put(object, name);
			try {
				Class[] parameterTypes = {String.class};
				String[] names = name.split("\\?");
				for (String subname : names) {
					String methodName = "set" + subname.replaceFirst(".*-", "");
					Method setMethod = object.getClass().getMethod(
							methodName, parameterTypes);
					String value = getString(subname);
					if (methodName.equals("setToolTipText")) {
						value = generateToolTipText(value);
					}
					setMethod.invoke(object, value);
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}

}
